package com.mjduan.myBank.user.dao.daoImpl;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.mjduan.myBank.user.dao.IUserDao;
import com.mjduan.myBank.util.dao.BaseDaoImpl;
import com.mjduan.myBank.util.entity.User;

@Component("UserDaoImpl")
@Transactional(rollbackFor = Exception.class)
public class UserDaoImpl extends BaseDaoImpl<User> implements IUserDao {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    /**
     * 若没有查询到则返回null。
     * 若查询到User，则返回全新的User(属性值与数据库中的记录一致)
     */
    @Override
    public User findUserByAccountAndPassword(User user) {
        String hql = "from User where account=? and password=?";
        Object[] params = {user.getAccount(), user.getPassword()};
        List<User> users = (List<User>) hibernateTemplate.find(hql, params);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public boolean addUser(User user) {
        Serializable id = hibernateTemplate.save(user);
        return true;
    }

    @Override
    public boolean isEmailUsed(String email) {
        User user = new User();
        user.setEmail(email);
        List<User> result = hibernateTemplate.findByExample(user);
        return !result.isEmpty();
    }

    @Override
    public boolean isNameUsed(String name) {
        User user = new User();
        user.setName(name);
        List<User> result = hibernateTemplate.findByExample(user);
        return !result.isEmpty();
    }

    @Override
    public boolean updateUserStatus(int id, String password, int newStatus) {
        String hql = "update User set status=? where id=?";
        int update = hibernateTemplate.bulkUpdate(hql, newStatus, (long) id);
        return update > 0;
    }
}
